package com.company.permission.servlet;

import com.company.permission.dao.UserDao;
import com.company.permission.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 移除 @WebServlet 注解，在web.xml中配置
public class UserServlet extends BaseServlet {

    private UserDao userDao = new UserDao();

    /**
     * 任务一：查询特定用户及其拥有的所有角色
     */
    public void getUserWithRoles(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String username = req.getParameter("username");
        if (username == null || username.trim().isEmpty()) {
            sendError(resp, "用户名不能为空");
            return;
        }

        try {
            User user = userDao.findUserWithRolesByUsername(username);
            if (user != null) {
                sendSuccess(resp, user);
            } else {
                sendError(resp, "用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendError(resp, "查询用户失败: " + e.getMessage());
        }
    }

    /**
     * 任务三：根据条件搜索用户，并连带其角色和权限信息
     */
    public void searchUsers(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String statusStr = req.getParameter("status");
        Integer status = null;

        if (statusStr != null && !statusStr.trim().isEmpty()) {
            try {
                status = Integer.parseInt(statusStr);
            } catch (NumberFormatException e) {
                sendError(resp, "状态参数格式错误");
                return;
            }
        }

        try {
            List<User> users = userDao.findUsersWithRolesAndMenusByCondition(username, email, status);
            sendSuccess(resp, users);
        } catch (Exception e) {
            e.printStackTrace();
            sendError(resp, "搜索用户失败: " + e.getMessage());
        }
    }
}